#include <assert.h>
#include <irrlicht.h>
#include "demo.h"
#include "fx_aivop.h"


using namespace irr;
using namespace irr::core;
using namespace irr::scene;


static ISceneManager *sSceneManager = 0;
static ISceneNode *sAivot = 0;


bool AivopFx::init()
{
    if (!gIrrDevice || !gIrrDevice->getSceneManager())
        return false;

    //bool zipRes = gIrrDevice->getFileSystem()->addFileArchive("data_oldies_aivoptest.zip", false, false, io::EFAT_ZIP);
    //assert(zipRes);

    sSceneManager = gIrrDevice->getSceneManager()->createNewSceneManager();

    ISceneManager *sceneManager = sSceneManager;

    sceneManager->loadScene("data/oldies/aivoptest.irr");

    ISceneNode *light = sceneManager->getSceneNodeFromType(scene::ESNT_LIGHT);

    sAivot = sceneManager->getSceneNodeFromName("aivot");

    sceneManager->addCameraSceneNode();
    vector3df cameraPosition = light->getPosition();
    cameraPosition.Y /= 2;
    sceneManager->getActiveCamera()->setPosition(cameraPosition);
    sceneManager->getActiveCamera()->setTarget(sAivot->getPosition());

    sAivot->getMaterial(0).setFlag(video::EMF_LIGHTING, true);
    assert(sAivot->getType() == scene::ESNT_MESH || sAivot->getType() == scene::ESNT_ANIMATED_MESH);
    IMeshSceneNode *aivotMSN = (IMeshSceneNode *)sAivot;
    sceneManager->getMeshManipulator()->recalculateNormals(aivotMSN->getMesh(), true, true);
    //sceneManager->getMeshManipulator()->setVertexColors(sCube->getMesh(), video::SColor(0xffffeedd));

    mInitialized = true;
    return true;
}


void AivopFx::render(double time, int timeMs)
{
    vector3df eulerAngles(0, (float)gTimeMs / 20.0f, 0);
    sAivot->setRotation(eulerAngles);

    ISceneNode *light = sSceneManager->getSceneNodeFromType(scene::ESNT_LIGHT);
    vector3df cameraPosition = light->getPosition();
    cameraPosition.Y *= 1.0f - sBoxStep((float)time, (float)mFxStartTime, (float)mFxEndTime);
    sSceneManager->getActiveCamera()->setPosition(cameraPosition);
    sSceneManager->getActiveCamera()->setTarget(sAivot->getPosition());

    const float endTransitionLength = (float)(mRenderEndTime - mFxEndTime);
    float fxEndTransitionScale = 1.0f - sBoxStep((float)time, (float)mFxEndTime, (float)mFxEndTime + endTransitionLength);
    sAivot->setScale(vector3df(fxEndTransitionScale, fxEndTransitionScale, fxEndTransitionScale));
	sSceneManager->drawAll();
}


void AivopFx::deinit()
{
    sSceneManager->drop();
    mInitialized = false;
}
